﻿using RealidadeAumentada.Entidades;

namespace RealidadeAumentada.Servicos.Analise.Histograma
{
    public class LimiteDiscriminante : ILimite
    {
        private double _pontuacao;

        public int ObterLimite(EHistograma i_histogram)
        {
            int[] hist = i_histogram.data;
            int n = i_histogram.length;
            int da, sa, db, sb, dt, pt, st;
            int i;
            int th = 0;
            dt = pt = 0;
            for (i = 0; i < n; i++)
            {
                int h = hist[i];
                dt += h * i;
                pt += h * i * i;
            }
            st = i_histogram.total_of_data;
            
            da = dt;
            sa = st;
            
            db = sb = 0;

            double max = -1;
            double max_mt = 0;
            
            for (i = n - 1; i > 0; i--)
            {
                int hist_count = hist[i];
                int hist_val = hist_count * i;
                da -= hist_val;
                sa -= hist_count;
                db += hist_val;
                sb += hist_count;

                double dv = (sa + sb);
                double mt = (double)(da + db) / dv;
                double ma = (sa != 0 ? ((double)da / (double)sa) : 0) - mt;
                double mb = (sb != 0 ? ((double)db / (double)sb) : 0) - mt;
                double kai = ((double)(sa * (ma * ma) + sb * (mb * mb))) / dv;
                if (max < kai)
                {
                    max_mt = mt;
                    max = kai;
                    th = i;
                }
            }
            this._pontuacao = max / ((double)(pt + max_mt * max_mt * st - 2 * max_mt * dt) / st);//129,0.8888888888888887
            return th;
        }

        public double ObterUltimaPontuacao()
        {
            return this._pontuacao;
        }
    }
}
